﻿$(document).ready(function () {

    $("input[id$=searchTextBox]").watermark("search person, place or thing");
    $("#divLogo").click(function () {
        location.href = "Index.aspx";
    });
    $("#logOut").click(function () {
        onLogout();
    });
    $(".menu").css("visibility", "visible");

    $(".dropdown dt a").click(function () {
        // Change the behaviour of onclick states for links within the menu.
        var toggleId = "#" + this.id.replace(/^link/, "ul");
        // Hides all other menus depending on JQuery id assigned to them
        $(".dropdown dd ul").not(toggleId).hide();
        //Only toggles the menu we want since the menu could be showing and we want to hide it.
        $(toggleId).toggle();
        //Change the css class on the menu header to show the selected class.
        if ($(toggleId).css("display") == "none") {
            $(this).removeClass("selected");
        } else {
            $(this).addClass("selected");
        }
    });

    $(".dropdown dd ul li a").click(function () {
        // This is the default behaviour for all links within the menus
        var text = $(this).html();
        $(".dropdown dt a span").html(text);
        $(".dropdown dd ul").hide();
    });

    $(document).bind('click', function (e) {
        // Lets hide the menu when the page is clicked anywhere but the menu.
        var $clicked = $(e.target);
        if (!$clicked.parents().hasClass("dropdown")) {
            $(".dropdown dd ul").hide();
            $(".dropdown dt a").removeClass("selected");
        }

    });

    $("#profileCommentTextBox").keyup(function (e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) { //Enter keycode

            var pId = $("#hidPid").val();
            var comment = $(this).val();
            if ($.trim(comment).length > 0)
                makeAJAXCall("POST", "ProfileDetail.aspx/AddProfileComments", "{profileId:" + pId + ", comment:'" + comment + "'}", OnProfileCommentAdded, OnProfileCommentError);
        }
    });

    $("input[id$=searchTextBox]").keyup(function (e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        var search = $("input[id$=searchTextBox]");
        var keywords = search.val();
        if (keywords.length >= 1) {
            CallHttpHandler("POST", "Handler/SearchHandler.ashx", "{keywords:'" + keywords + "'}", OnSearch, OnSearchError);
        }
        $('#divSearchResult').show();

    });

    $(document).click(function (e) {
        if ($(e.target).is('#divSearchResult *')) return;
        $('#divSearchResult').hide();
    });  
    

});

//end ready function

var tb_pathToImage = "images/ajax-loader.gif";
var commentList_markup = '<li>\
                             <span id="spnFrom" class="from">{fromData}</span>\
                             <div id="divCommentText" class="comments">{commentData}</div>\
                             <div id="divDate" class="date">{dateData}</div>\
                             </li>';

var ul_MarkUP = "<ul id='ulPCmt'>{commentList}</ul>";

    function SetSideBarMainContentHeightEql(sideDiv, mainDiv,rightDiv, isLeftBorderRequired) {
        var h1 = $(sideDiv).height();
        var h2 = $(mainDiv).height();

        if (h1 > h2) {
            $(mainDiv).height(h1 - 1);
        }
        else {
            $(sideDiv).height(h2);
        }
        if (!isLeftBorderRequired) {
            $(sideDiv).addClass('no-left-Border');
        }

        if ($.isEmptyObject(rightDiv) == false) {
            var container = $('#container').height();

            var h3 = $(rightDiv).height();            
            if (container >= h2 & container >= h3) {
                $(rightDiv).height(container);
                $(mainDiv).css({"min-height":container});
            }         
        }
    }

    function GetImageCarousel(profileId) {
        ShowLoader();
        makeAJAXCall("POST", "ProfileDetail.aspx/LoadFiles", "{profileId:" + profileId + ",typeId:1}", DisplayImageBox, OnError);
    }
    function GetVidCarousel(profileId) {
        ShowLoader()
        makeAJAXCall("POST", "ProfileDetail.aspx/LoadFiles", "{profileId:" + profileId + ",typeId:2}", DisplayImageBox, OnError);
    }

    function ShowLoader() {
        imgLoader = new Image(); // preload image
        imgLoader.src = tb_pathToImage;
        $("body").append("<div id='Overlay'><div id='TB_load'><img src='" + imgLoader.src + "' /></div></div>"); //add loader to the page
        $('#Overlay').show();
        $('#TB_load').show();
    }
    function RemoveLoader() {
        $("#Overlay").remove();
        $("#TB_load").remove();
    }
    function DisplayImageBox(response) {

        $('#divDynamicContent').empty();

        if (parseInt(response.d.length) > 0) {
            $('#divDynamicContent').append("<div id='wrap' class='clear'><ul id='mycarousel' class='jcarousel-skin-tango'>");
            PopulateContent(response.d);
            $('#divDynamicContent').append("</ul></div>");
            $("a[rel^='prettyPhoto']").prettyPhoto();
            $('#divDynamicContent').removeClass("display-none");
            $('#mycarousel').jcarousel();
            RemoveLoader();
        }
        else {
            $('#divDynamicContent').removeClass("display-none");
            $('#divDynamicContent').addClass("clear jcarousel-skin-tango");
            $('#divDynamicContent').append("<div class='error' >No file available at this moment.</div>");
            
            RemoveLoader();
        }

    }

    function OnError(msg) {
        $('#divDynamicContent').append("<div id='wrap' class='jcarousel-container error' style='position: relative; display: block;'></div>");
        $('#wrap').html(msg);
    }
    function PopulateContent(files) {

        $.each(files, function (index, file) {
            if (file.Entity_Type_MST_ID == 1)
                $('#mycarousel').append('<li style="padding-right:0px;"><a href=' + file.File_Path + ' rel="prettyPhoto[pp_gal]" title=\"' + file.File_Name + '"\ id=' + file.File_Id + '><img src=' + 'Handler/ImageHandler.ashx?image=' + file.File_Path + '&width=120&height=120' + ' alt=\"' + file.File_Name + '"\ desc=\"' + file.File_Desc + '"\ style="padding-right:0px;border:0px;" /></a></li>');
            else if (file.Entity_Type_MST_ID == 2) {
                var qsIndex = file.File_Path.indexOf("?v=");
                var id = file.File_Path.slice(qsIndex + 3, file.File_Path.length);
                var vidImgUrl = "http://img.youtube.com/vi/" + id + "/1.jpg";

                $('#mycarousel').append('<li style="padding-right:0px;"><a href=' + file.File_Path + ' rel="prettyPhoto[pp_gal]" title=\"' + file.File_Name + '"\ id=' + file.File_Id + '><img src=' + vidImgUrl + ' alt=\"' + file.File_Name + '"\ desc=\"' + file.File_Desc + '"\ style="padding-right:0px;border:0px;" /></a></li>');
            }
        });

    }

    function newsSearchComplete() {

        // Check that we got results
        $('#divDynamicContent').empty();
        $('#divDynamicContent').removeClass("display-none");
        $('#divDynamicContent').addClass("clear jcarousel-skin-tango");
        
        if (newsSearch.results && newsSearch.results.length > 0) {

            var ul = document.createElement('ul');
            for (var i = 0; i < newsSearch.results.length; i++) {

                // Create HTML elements for search results
                var li = document.createElement('li');
                var a = document.createElement('a');
                a.target = "_blank";
                a.href = unescape(newsSearch.results[i].url);
                a.innerHTML = newsSearch.results[i].title;

                // Append search results to the HTML nodes
                li.appendChild(a);
                ul.appendChild(li);

            }
            var disp = query.replace(",", " aka ");
            $('#divDynamicContent').append("<p id='newsHeader'> News on " + disp + "<span id='branding' style='float:right;'></span></p>");
            $('#divDynamicContent').append("<div id='wrap' class='jcarousel-container news-container-horizontal' style='position: relative; display: block;overflow:auto;'></div>");
            $('#wrap').append(ul);
            // Include the required Google branding
            google.search.Search.getBranding('branding');
            RemoveLoader();
        }
        else {           
            $('#divDynamicContent').addClass("clear jcarousel-skin-tango");
            $('#divDynamicContent').append("<div class='error' >No file available at this moment.</div>");
            RemoveLoader();
        }
    }   
    
    function makeAJAXCall(callType, method, data, onSuccess, onFailure) {
        $.ajax({
            type: callType,
            url: method,
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: onSuccess,
            failure: onFailure
        });
    }
    function CallHttpHandler(callType, method, data, onSuccess, onFailure) {        
        $.ajax({
            type: callType,
            url: method,
            data: data,
            dataType: "json",
            success: onSuccess,
            failure: onFailure
        });
    }
    function getUrlVars() {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        
        for (var i = 0; i < hashes.length; i++) {
            
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1].replace('#','');
        }
        return vars;
    }
    var id;
    function loadProfileComments(profileId) {
        id = profileId;
        makeAJAXCall("POST", "ProfileDetail.aspx/LoadProfileComments", "{profileId:" + profileId + "}", DisplayProfileComments, OnProfileCommentError);
    }

    function DisplayProfileComments(response) {

        comments = response.d;
        //alert(comments);
        var commentToInject = "", liList = "", ulCommentList="";
        var len = parseInt(comments.length);

        if (len > 0) {
            hasComment = true;
            $.each(comments, function (index, comment) {
                
                commentToInject = commentList_markup.replace(/{fromData}/g, comment.User.First_Name + " " + comment.User.Last_Name);
                commentToInject = commentToInject.replace(/{commentData}/g, comment.Profile_Comment);
                

                cmtTime = $.localtime.toLocalTime(comment.Created_Date + "Z","dd MMM yyyy HH:mm:ss"); //z added for UTC Standard format
                
                commentToInject = commentToInject.replace(/{dateData}/g, cmtTime);

                liList += commentToInject;
               

            });
            
            ulCommentList = ul_MarkUP.replace(/{commentList}/g, liList);
            $('#divProfile_comments').append(ulCommentList);
            $("#profileCommentTextBox").watermark("Add a comment...");

        }
        else {
            hasComment = false;
            ulCommentList = ul_MarkUP.replace(/{commentList}/g, "");
            $('#divProfile_comments').append(ulCommentList);

            $("#profileCommentTextBox").watermark("Be the first one to comment...");
        }
        EnableDisableProfileCommentWriting(hasComment);


    }
    function EnableDisableProfileCommentWriting(hasComment) {
        FB.getLoginStatus(function (response) {
            if (response.status == "connected") {
                $("#profileCommentTextBox").removeAttr("disabled");
                if(hasComment)
                    $("#profileCommentTextBox").watermark("Add a comment...");
                else
                    $("#profileCommentTextBox").watermark("Be the first one to comment...");

            }
            else {
                $("#profileCommentTextBox").watermark("Login to comment...");
                $("#profileCommentTextBox").attr("disabled", "disabled");               

            }
        });
    }

    function OnProfileCommentError(msg) {
        
        var ulList = ul_MarkUP.replace(/{commentList}/g, msg);
        $('#divProfile_comments').append(ulList);
        $("#profileCommentTextBox").watermark("Add a comment...");
    }   

    function OnProfileCommentAdded(response) {
        var comment = response.d;

        commentToInject = commentList_markup.replace(/{fromData}/g, comment.User.First_Name + " " + comment.User.Last_Name);
        commentToInject = commentToInject.replace(/{commentData}/g, comment.Profile_Comment);
        cmtTime = $.localtime.toLocalTime(comment.Created_Date + "Z","dd MMM yyyy HH:mm:ss");
        commentToInject = commentToInject.replace(/{dateData}/g, cmtTime);
       
        var ulcmt = $("#ulPCmt");
        ulcmt.append(commentToInject);
        ulcmt.scrollTop(ulcmt.get(0).scrollHeight);
        $("#profileCommentTextBox").val("");

    }

    function OnSearch(response) {
        var profiles = response;
        //console.log(response);
        PopulateSearchResult(profiles);
    }

    function OnSearchError(msg) {
        alert(msg);
       // $('#divSearchResult').find("#ulSearch").append('<li style="padding-right:0px;">\"' + msg +'"\</li>');
    }

    function PopulateSearchResult(profiles) {
        var sc = $('#divSearchResult').find("#ulSearch");
        sc.empty();
        $.each(profiles, function (index, profile) {
            if (index < 10)
                sc.append('<li><a href=\"ProfileDetail.aspx?cid=' + profile.Category_Id + '&pid=' + profile.Profile_Id + '"\ title=\"' + profile.Profile_Title + " also know as " + profile.Profile_AKA + '"\ id=' + profile.Profile_Id + '><img src=' + 'Handler/ImageHandler.ashx?profileId=' + profile.Profile_Id + '&width=30&height=30&issearch=true' + ' alt=\"' + profile.Profile_AKA + '"\/><span> ' + profile.Profile_Title + '</span></a></li>');
            else {
                var search = $("input[id$=searchTextBox]");
                sc.append('<li><a href=\"SearchResult.aspx?search=' + escape(search.val()) + '"\><p>View more results...</p></a></li>');
                return false;
            }
        });

    }